#pragma once
#include<iostream>
#include<vector>

using namespace std;

namespace wxh
{
	template<class K, class V>
	struct HashNode
	{
		pair < K, V> _kv;
		HashNode* _next;

		HashNode(const pair<K, V>& kv)
		{
			_kv = kv;
			_next = nullptr;
		}
	};

	template<class K>
	struct Setkey
	{
		size_t operator()(const K& key)
		{
			return (size_t)key;
		}
	};

	template<>
	struct Setkey<string>
	{
		size_t operator()(const string& key)
		{
			size_t sum = 0;
			for (auto ch : key)
			{
				sum *= 131;
				sum += ch;
			}
			return sum;
		}
	};

	template<class K, class V,class Setkey=Setkey<K>>
	class HashBucket
	{
	public:
		HashBucket()
		{
			_tables.resize(10);
		}

		~HashBucket()
		{
			for (int i = 0; i < _tables.size(); i++)
			{

				HashNode<K, V>* cur = _tables[i];
				while (cur)
				{
					HashNode<K, V>* temp = cur;
					cur = cur->_next;
					delete temp;
				}
			}
			_n = 0;
		}

		bool Insert(const pair<K, V>& kv)
		{
			if (Find(kv.first))
			{
				return false;
			}

			if (_n * 10 / _tables.size() >= 7)
			{
				HashBucket<K, V> newhash;
				newhash._tables.resize(_tables.size()*2);
				for (int i = 0; i < _tables.size(); i++)
				{
					HashNode<K, V>* cur = _tables[i];
					while (cur)
					{
						newhash.Insert(cur->_kv);
						cur = cur->_next;
					}
				}

				_tables.swap(newhash._tables);

			}

			Setkey h;

			size_t hashi = h(kv.first) % _tables.size();
			HashNode<K, V>* cur = _tables[hashi];
			HashNode<K, V>* newnode = new HashNode<K,V>(kv);
			_tables[hashi] = newnode;
			newnode->_next = cur;
			_n++;
		}

		HashNode<K, V>* Find(const K& key)
		{
			Setkey h;
			size_t hashi = h(key) % _tables.size();
			HashNode<K, V>* cur = _tables[hashi];
			while (cur)
			{
				if (cur->_kv.first == key)
				{
					return cur;
				}
				cur = cur->_next;
			}
			return nullptr;
		}

		bool Erase(const K& key)
		{
			Setkey h;
			size_t hashi = h(key) % _tables.size();
			HashNode<K, V>* cur = _tables[hashi];
			HashNode<K, V>* parent = nullptr;
			while (cur)
			{
				
				if (cur->_kv.first == key)
				{
					if (parent == nullptr)
					{
						HashNode<K, V>* temp = cur->_next;
						_tables[hashi] = temp;
					}
					else
					{
						parent->_next = cur->_next;
					}
					delete cur;
					return true;
				}
				parent = cur;
				cur = cur->_next;
			}
			return false;
		}

		void Print()
		{
			for (size_t i = 0; i < _tables.size(); i++)
			{
				HashNode<K, V>* cur = _tables[i];
				cout << "[" << i << "]->";
				while (cur)
				{
					cout << cur->_kv.first << ":" << cur->_kv.second << "   ";
					cur = cur->_next;
				}
				cout << endl;
			}
			cout << endl;
		}

	private:
		vector<HashNode<K, V>*> _tables;
		size_t _n = 0;
	};
}
